package com.kfm.hotel.interceptor;

import com.anji.captcha.util.AESUtil;
import com.kfm.hotel.domain.SysUser;
import com.kfm.hotel.service.SysUserService;
import com.kfm.hotel.util.Constant;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RememberMeInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 先判断 session 中是否有用户信息
        Object user = request.getSession().getAttribute(Constant.LOGIN_USER);
        if (user != null){
            // 已登录，重定向到首页
            response.sendRedirect("/index");
            return false;
        }

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            // 判断是否有 rememberMe 的 cookie
            if (Constant.REMEMBER_ME_COOKIE_NAME.equals(cookie.getName())){
                String[] split = cookie.getValue().split("--");
                String username = AESUtil.aesDecrypt(split[0], Constant.REMEMBER_ME_AES_KEY);
                String password = AESUtil.aesDecrypt(split[1], Constant.REMEMBER_ME_AES_KEY);
                SysUser login1 = service.login(username, password);
                if (login1 != null){
                    // 登录成功，重定向到首页
                    request.getSession().setAttribute(Constant.LOGIN_USER, login1);
                    response.sendRedirect("/index");
                    return false;
                }
            }
        }
        return true;
    }
}
